import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;

import java.util.concurrent.atomic.AtomicLong;

public class NettyWebServer {
    private static final AtomicLong reqCount = new AtomicLong(0);
    private static final EventExecutorGroup VIRTUAL_THREAD_GROUP =
//            new DefaultEventExecutorGroup(NettyRuntime.availableProcessors());
            new DefaultEventExecutorGroup(1000,
                    r -> Thread.ofVirtual().name("netty-virtual-", 0).unstarted(r));

    public static void main(String[] args) throws Exception {
        int port = 8082;

        // 创建事件循环组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new HttpServerCodec());
                            pipeline.addLast(new HttpObjectAggregator(65536));
                            pipeline.addLast(VIRTUAL_THREAD_GROUP, new AdvancedVirtualThreadHandler());
                        }
                    });

            // 绑定端口并启动
            ChannelFuture future = bootstrap.bind(port).sync();
            System.out.println("服务器启动成功，访问: http://0.0.0.0:" + port + "/test");

            // 等待服务器通道关闭
            future.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    // 计算第 N 个斐波那契数 (迭代/非递归，避免栈溢出，专注于CPU循环)
    private static long cpuIntensiveTask(int n) {
        if (n <= 1) return n;

        int limit = n * 100000+1;
        long a = 0;
        long b = 1;
        long c = 1;

        for (int i = 2; i < limit; i++) {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
    // 模拟I/O密集型任务
    private static void ioBoundTask() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    // 简单的HTTP请求处理器
    private static class AdvancedVirtualThreadHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
        private void sendResponse(ChannelHandlerContext ctx, String responseText) {
            FullHttpResponse response = new DefaultFullHttpResponse(
                    HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK,
                    Unpooled.copiedBuffer(responseText, CharsetUtil.UTF_8)
            );

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());

            ctx.writeAndFlush(response);
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
            String responseText = handleRequestWithVirtualThread(request);
            sendResponse(ctx, responseText);
        }

        private String handleRequestWithVirtualThread(FullHttpRequest request) {
            long count = reqCount.getAndAdd(1);
            try {
                if ("/test".equals(request.uri())) {
                    // 1. 模拟I/O等待
                    ioBoundTask();
                    // 2. 模拟CPU计算
                    long tmpRandN = count%50;
                    long result = cpuIntensiveTask((int) tmpRandN);
                    //System.out.println("Count:"+count +" RandN:"+tmpRandN+ " Hash:"+result);
                    return "{\"hash\":" + result + ",\"count\":"+count+", \"message\": \"Processed successfully by Java\"}";
                } else {
                    return "{\"error\": \"uri not found! \"}";
                }
            }catch (Exception e) {
                return String.format("{\"error\": \"%s\"}", e.getMessage());
            }
        }
    }


}